package com.english.controller;

import cn.hutool.core.util.StrUtil;
import com.english.common.CommonResponse;
import com.english.domain.UserDTO;
import com.english.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;

    @PostMapping("/login")
    public CommonResponse login(@RequestBody UserDTO userDTO){
        String userid = userDTO.getUserid();
        String password = userDTO.getPassword();
        //通过hutool 的工具类对是否为空进行判断
        if (StrUtil.isBlank(userid) || StrUtil.isBlank(password)){
            //调用common中的错误函数进行数据包装
            return CommonResponse.createForError("参数错误");
        }
        UserDTO dto = userService.login(userDTO);
        dto.setPassword(null);
        if(dto == null)return CommonResponse.createForError("用户名或密码错误");
        return CommonResponse.createForSuccess(dto);
    }
    @PostMapping("/register")
    public CommonResponse register(@RequestBody UserDTO userDTO){
        System.err.println(userDTO);
        //参数校验
        if( userDTO.valid() ){
            return CommonResponse.createForError("参数不符合格式");
        }
        userDTO = userService.register(userDTO);
        if( userDTO == null ){
            return CommonResponse.createForError("用户已存在");
        }
        return CommonResponse.createForSuccess("注册成功",userDTO);
    }
    @GetMapping("/homepage")
    public CommonResponse homepage(@RequestHeader("token") String token){
        UserDTO userDTO = userService.getInfo(token);
        if(userDTO == null ){
            return CommonResponse.createForError("错误!");
        }
        else return CommonResponse.createForSuccess(userDTO);
    }
}
